import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class PrivacyPolicyController extends GetxController {
  PrivacyPolicyController();

  // WebView控制器
  late final WebViewController webViewController;
  
  // 页面标题
  String title = '';
  
  // 页面URL
  String url = '';
  
  // 加载状态
  final isLoading = true.obs;
  
  // 加载进度 (0-100)
  final loadingProgress = 0.obs;
  
  // 错误状态
  final hasError = false.obs;
  
  /// 更新加载进度
  void updateLoadingProgress(int progress) {
    loadingProgress.value = progress;
  }
  
  /// 设置加载状态
  void setLoading(bool loading) {
    debugPrint('PrivacyPolicy 加载状态: $loading');
    isLoading.value = loading;
    if (loading) {
      hasError.value = false;
    }
  }
  
  /// 设置错误状态
  void setError(bool error) {
    debugPrint('PrivacyPolicy 错误状态: $error');
    hasError.value = error;
    if (error) {
      isLoading.value = false;
    }
  }
  
  /// 重新加载页面
  void reload() {
    webViewController.reload();
  }

  @override
  void onInit() {
    super.onInit();
    debugPrint('PrivacyPolicyController onInit');
    
    // 获取路由参数
    final Map<String, dynamic> args = Get.arguments ?? {'type': 'userManual'};
    final String type = args['type'] as String? ?? 'userManual';
    
    // 根据类型设置标题和URL
    if (type == 'privacyPolicy') {
      title = '隐私政策';
      url = 'http://app.playtruly.cn/%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96.html';
    } else {
      title = '用户手册';
      url = 'http://app.playtruly.cn/%E7%94%A8%E6%88%B7%E6%89%8B%E5%86%8C.html';
    }
    
    debugPrint('加载URL: $url');
    
    // 初始化WebView控制器
    webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('PrivacyPolicy 加载进度: $progress');
            updateLoadingProgress(progress);
          },
          onPageStarted: (String url) {
            debugPrint('PrivacyPolicy 页面开始加载: $url');
            setLoading(true);
          },
          onPageFinished: (String url) {
            debugPrint('PrivacyPolicy 页面加载完成: $url');
            setLoading(false);
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('PrivacyPolicy 加载错误: ${error.description}');
            debugPrint('错误代码: ${error.errorCode}');
            debugPrint('错误类型: ${error.errorType}');
            if (error.description.contains('ERR_CLEARTEXT_NOT_PERMITTED')) {
              debugPrint('明文HTTP流量被阻止，检查Android网络安全配置');
            }
            setError(true);
          },
        ),
      )
      ..loadRequest(Uri.parse(url));
  }

  @override
  void onReady() {
    super.onReady();
    debugPrint('PrivacyPolicyController onReady');
  }

  @override
  void onClose() {
    debugPrint('PrivacyPolicyController onClose');
    super.onClose();
  }
}
